package com.rsscollector.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class Log4JUtil {
	
	public static Collection<Appender> getAllAppenders() {
		
		/* Get loggers */
        List<Logger> loggers = new ArrayList<Logger>();
        Enumeration e = LogManager.getCurrentLoggers();
        for (; e.hasMoreElements(); ) {
            loggers.add((Logger) e.nextElement());
        }
        loggers.add(LogManager.getRootLogger());
        
        /* Get appenders */
        Map<String, Appender> appenderMap = new Hashtable<String, Appender>();
        for (Iterator<Logger> it = loggers.iterator(); it.hasNext();) {
			Logger logger = (Logger) it.next();
	        Enumeration e2 = logger.getAllAppenders();
	        for (; e2.hasMoreElements(); ) {
	            Appender appender = (Appender) e2.nextElement();
	            appenderMap.put(appender.getName(), appender);
	        }
		}
        
        return appenderMap.values();
	}

	public static Collection<FileAppender> getAllFileAppenders() {
		Collection<FileAppender> fileAppenders = new ArrayList<FileAppender>();
		
		for (Iterator<Appender> it = Log4JUtil.getAllAppenders().iterator(); it.hasNext();) {
			Appender appender = it.next();
			if (appender instanceof FileAppender) {
				fileAppenders.add((FileAppender) appender);
			}
		}
		return fileAppenders;
	}
}
